package ua.yandex.bank;

import java.util.concurrent.locks.*;
import java.util.*;

public class Bank {

    private List<Account> accounts;
    private Lock bankLock = new ReentrantLock();
    private Condition sufficientFunds = bankLock.newCondition();

    public Bank() {
        accounts = new ArrayList<Account>();
    }

    public void addAccount(Account account) {
        accounts.add(account);
    }

    public Account getAccount(String id) {
        for (Account acc : accounts) {
            if (acc.getId().equals(id)) {
                return acc;
            }
        }
        return null;
    }

    public int getTotalBalance() {
        int sum = 0;
        for (Account temp : accounts) {
            sum += temp.getBalance();
        }
        return sum;
    }

    public void transfer(Account from, Account to, int ammount)
            throws NotMoneyException {
        bankLock.lock();
        try {
            while (from.getBalance() < ammount) {
                sufficientFunds.await();
            }
            sufficientFunds.signalAll();
            from.withdraw(ammount);
            to.deposit(ammount);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bankLock.unlock();
        }
    }
}
